<template>
  <layout-content header="Storage Class">
    <div style="float: left">
      <el-button
        v-has-permissions="{
          scope: 'cluster',
          apiGroup: 'storage.k8s.io',
          resource: 'storageclasses',
          verb: 'create'
        }"
        type="primary"
        size="small"
        @click="onShouldCreate"
      >
        YAML
      </el-button>
      <el-button
        v-has-permissions="{
          scope: 'cluster',
          apiGroup: 'storage.k8s.io',
          resource: 'storageclasses',
          verb: 'delete'
        }"
        type="primary"
        size="small"
        :disabled="selections.length === 0"
        @click="onDeleteSecret()"
      >
        {{ $t("commons.button.delete") }}
      </el-button>
    </div>
    <complex-table
      v-model:selects="selections"
      v-loading="uiState.loading"
      :data="storageClassList"
      :pagination-config="query.paginationConfig"
      :search-config="query.searchConfig"
      @search="reloadSecretList"
    >
      <el-table-column type="selection" fix />
      <el-table-column
        :label="$t('commons.table.name')"
        prop="metadata.name"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <span class="span-link" @click="onShouldViewDetails(row)">
            {{ row.metadata.name }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('business.storage.provisioner')"
        prop="provisioner"
      >
        <template #default="{ row }">
          {{ row.provisioner }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('business.storage.reclaimPolicy')"
        prop="reclaimPolicy"
      >
        <template #default="{ row }">
          {{ row.reclaimPolicy }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('business.storage.default')">
        <template #default="{ row }">
          <i v-if="isDefaultStorageClass(row)" class="el-icon-check" />
          <i v-else class="el-icon-minus" />
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('commons.table.created_time')"
        prop="metadata.creationTimestamp"
        fix
      >
        <template #default="{ row }">
          {{ row.metadata.creationTimestamp }}
        </template>
      </el-table-column>
      <ko-table-operations
        :buttons="uiState.buttons"
        :label="$t('commons.table.action')"
      />
    </complex-table>
  </layout-content>
</template>

<script setup lang="ts">
import LayoutContent from "@/views/domain/kubeHud/views/components/layout/LayoutContent.vue";
import ComplexTable from "@/views/domain/kubeHud/views/components/complex-table/index.vue";
import KoTableOperations from "@/views/domain/kubeHud/views/components/ko-table-operations/index.vue";
import { onMounted, reactive, ref } from "vue";
import {
  PresetAnnotationKey,
  Secret,
  StorageClass,
  useK8SApi
} from "@/views/domain/kubeHud/api/k8s";
import { useI18n } from "vue-i18n";
import { useVerifyRouter } from "@/router/use";
import { checkPermissions } from "@/views/domain/kubeHud/utils/permission";
import { ElMessage, ElMessageBox } from "element-plus";
import { KRouteStorageClass } from "@/views/domain/kubeHud/router";
import { saveYamlAsFile } from "@/views/domain/kubeHud/utils/file";
// import { downloadYaml } from "@/utils/actions";
// import {
//   changeStorageClass,
//   deleteStorageClasses,
//   getStorageClass,
//   listStorageClasses
// } from "@/api/storageclass";
// import { checkPermissions } from "@/utils/permission";

const { storageClassRepo } = useK8SApi();
const { t } = useI18n();

type Prop = {};
const props = withDefaults(defineProps<Prop>(), {});
const { router } = useVerifyRouter();
const storageClassList = ref<StorageClass[]>([]);
const selections = ref<StorageClass[]>([]);

const query = reactive({
  paginationConfig: {
    currentPage: 1,
    pageSize: 10,
    total: 0
  },
  searchConfig: {
    keywords: ""
  }
});

const uiState = reactive({
  loading: false,
  buttons: [
    {
      label: t("commons.button.edit"),
      icon: "el-icon-edit",
      click: row => {
        router.push({
          name: KRouteStorageClass.Create.name,
          params: { name: row.metadata.name },
          query: { yamlShow: false }
        });
      },
      disabled: async () => {
        return !(await checkPermissions({
          scope: "cluster",
          apiGroup: "storage.k8s.io",
          resource: "storageclasses",
          verb: "update"
        }));
      }
    },
    {
      label: t("business.storage.change_default"),
      icon: "el-icon-check",
      click: row => {
        toggleDefaultStorageClass(row);
      },
      disabled: async () => {
        return !(await checkPermissions({
          scope: "cluster",
          apiGroup: "storage.k8s.io",
          resource: "storageclasses",
          verb: "update"
        }));
      }
    },
    {
      label: t("commons.button.download_yaml"),
      icon: "el-icon-download",
      click: row => {
        storageClassRepo.getStorageClass({ data: row }).then(res => {
          saveYamlAsFile(res, `${row.metadata.name}.yaml`);
        });
      }
    },
    {
      label: t("commons.button.delete"),
      icon: "el-icon-delete",
      click: row => {
        onDeleteSecret(row);
      },
      disabled: async () => {
        return !(await checkPermissions({
          scope: "cluster",
          apiGroup: "storage.k8s.io",
          resource: "storageclasses",
          verb: "delete"
        }));
      }
    }
  ]
});

const reloadSecretList = async () => {
  selections.value = [];
  uiState.loading = true;
  try {
    const { items } = await storageClassRepo.listStorageClasses({});
    storageClassList.value = items;
  } catch (error) {
    console.log(error);
  } finally {
    uiState.loading = false;
  }
};

const onShouldCreate = () => {
  router.push({
    name: KRouteStorageClass.Create.name,
    query: { type: "storageclasses" }
  });
};

const onShouldViewDetails = (row: Secret) => {
  router.push({
    name: KRouteStorageClass.Details.name,
    query: { name: row.metadata.name, yamlShow: "false" }
  });
};

const onDeleteSecret = async (row?: Secret) => {
  if (row) {
    selections.value.push(row);
  }

  if (selections.value.length === 0) {
    ElMessage.error(t("commons.message_box.selectLeastOne"));
    return;
  }

  ElMessageBox.alert(
    t("commons.message_box.prompt"),
    `${t("commons.message_box.deleteConfirm")}${selections.value.map(e => e.metadata.name).join("、")}?`,
    {
      showCancelButton: true,
      confirmButtonText: t("commons.button.confirm"),
      cancelButtonText: t("commons.button.cancel"),
      type: "warning"
    }
  ).then(async () => {
    const batchRes = await Promise.all([
      ...selections.value.map(storageClass =>
        storageClassRepo.deleteStorageClasses({ data: storageClass })
      )
    ]);

    reloadSecretList();
  });
};

const toggleDefaultStorageClass = async (row: Secret) => {
  const currentIsDefault = isDefaultStorageClass(row);

  const updateBatchReqs: Promise<any>[] = [];
  updateBatchReqs.push(
    storageClassRepo.changeStorageClass(
      { data: row },
      {
        metadata: {
          annotations: {
            [PresetAnnotationKey.DefaultStorageClass]: currentIsDefault
              ? "false"
              : "true"
          }
        }
      }
    )
  );

  if (!currentIsDefault) {
    // 设置默认存储类,把其他的都设置为非默认 [??]
    //TODO: 该方法效率存疑
    const { items } = await storageClassRepo.listStorageClasses({
      namespace: row.metadata.namespace
    });

    updateBatchReqs.push(
      ...(items.map(storageClass =>
        storageClassRepo.changeStorageClass(
          {
            data: storageClass
          },
          {
            metadata: {
              annotations: {
                [PresetAnnotationKey.DefaultStorageClass]: "false"
              }
            }
          }
        )
      ) ?? [])
    );
  }
  await Promise.all(updateBatchReqs);
};

const isDefaultStorageClass = (row: Secret) => {
  return (
    row.metadata.annotations &&
    row.metadata.annotations[PresetAnnotationKey.DefaultStorageClass] === "true"
  );
};

onMounted(() => {
  reloadSecretList();
});
</script>

<style scoped></style>
